package com.chwn.curiousdiary.ui.register;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.ui.login.LoginActivity;
import com.chwn.curiousdiary.ui.main.MainActivity;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.api.IUserApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.gloable.User;
import com.chwn.curiousdiary.utils.CustomToast;
import com.chwn.curiousdiary.utils.DialogUtil;
import com.chwn.harulib.base.BaseActivity;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.util.ToastUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by Myshikin on 2017/6/18.
 */

public class PassWordActivity extends BaseActivity {

    @BindView(R.id.tv_suggest)
    TextView mSuggestTV;
    @BindView(R.id.et_pwd)
    EditText mPwdET;

    private String phone;
    private int    code;
    private int    mPageType;

    private String unionid;
    private User   user;
    private String passWord;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pwd;
    }

    public void onEventMainThread(CustomEvent event) {
        switch (event.getState()) {
            case CustomEvent.ClOSE_SELF:
                finish();
                if (EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().unregister(this);
                }
                break;
        }
    }

    @Override
    protected void initData() {
        super.initData();
        phone = getIntent().getStringExtra(Constant.PHONE);
        mPageType = getIntent().getIntExtra(Constant.JUMP_TYPE, Constant.BIND_PHONE);
        unionid = getIntent().getStringExtra(Constant.UNION_ID);
        code = getIntent().getIntExtra(Constant.VERIFY_CODE, -1);
        user = (User) getIntent().getSerializableExtra(Constant.USER);

    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        setBackTVisible(true);
        setBackIcon(R.drawable.icon_back_light);

        switch (mPageType) {
            case Constant.REGISTER:
            case Constant.BIND_PHONE:
                mSuggestTV.setText("请输入您的登录密码");
                mPwdET.setHint("登录密码");
                break;
            case Constant.FGT_PWD:
                mSuggestTV.setText("请输入您的新密码");
                mPwdET.setHint("输入新密码");
                break;
        }
    }

    @OnClick({R.id.ll_back, R.id.iv_next_step})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.iv_next_step:
                passWord = mPwdET.getText().toString();
                if (TextUtils.isEmpty(passWord)) {
                    ToastUtil.shortShowToast("请输入密码");
                    return;
                } else if (passWord.length() < Constant.MIN_NUM_PWD || passWord.length() > Constant.MAX_NUM_PWD) {
                    ToastUtil.shortShowToast("请输入6-18英文或数字密码");
                    return;
                }
                upPwd();
                break;
        }
    }

    private void upPwd() {
        IUserApi apiService = NetWork.getInstance()
                .getApiService(IUserApi.class);
        switch (mPageType) {
            case Constant.REGISTER:
                apiService
                        .userRegister(phone, passWord, Constant.OSTYPE, code)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                showWaitDialog("请稍等...");
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(mRegisterObserver);
                break;
            case Constant.FGT_PWD:
                apiService
                        .editUserPassword(phone, passWord, Constant.OSTYPE, code)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                showWaitDialog("请稍等...");
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(mFgtPwdObserver);
                break;
            case Constant.BIND_PHONE:
                apiService
                        .userBindPhone(phone, passWord, unionid, Constant.OSTYPE, code)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                showWaitDialog("请稍等...");
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(mObserver);
                break;
        }
    }


    private Observer<HttpResult<List<User>>> mObserver = new Observer<HttpResult<List<User>>>() {
        @Override
        public void onCompleted() {
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onNext(HttpResult<List<User>> result) {
            DialogUtil.dismissWaitDialog();
            if (result.getResult() == Constant.RESULT_ERROR) { //失败
                errAction(result.getErrorMessage());
                return;
            }

            List<User> resdata = result.getResdata();
            User user = resdata.get(0);

            user.setPassword(passWord);
            user.setIconNum(PassWordActivity.this.user.getIconNum());
            user.setKeepDay(PassWordActivity.this.user.getKeepDay());
            DiaryApplication.mInstance.saveUser(user);
            if (!TextUtils.isEmpty(user.getBabybirth())) {
                startActivity(new Intent(PassWordActivity.this, MainActivity.class));
            } else {
                Intent intent = new Intent(PassWordActivity.this, BabySexActivity.class);
                intent.putExtra(Constant.PHONE, phone);
                intent.putExtra(Constant.UNION_ID, unionid);
                startActivity(intent);
            }
        }
    };

    private Observer<HttpResult<Object>> mFgtPwdObserver = new Observer<HttpResult<Object>>() {
        @Override
        public void onCompleted() {
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onNext(HttpResult<Object> result) {
            DialogUtil.dismissWaitDialog();
            if (result.getResult() == Constant.RESULT_ERROR) { //失败
                errAction(result.getErrorMessage());
                return;
            }

            switch (mPageType) {
                case Constant.REGISTER: //返回登录界面
                    CustomToast.showShortToast("注册成功, 请登录");
                    break;
                case Constant.FGT_PWD: //返回登录界面
                    CustomToast.showShortToast("修改密码成功 , 请登录");
                    DiaryApplication.mInstance.saveUser(null);
                    break;
            }
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
            EventBus.getDefault().post(new CustomEvent(CustomEvent.ClOSE_SELF, 5));
            Intent resultIntent = new Intent(PassWordActivity.this, LoginActivity.class);
            startActivity(resultIntent);
            finish();
        }
    };

    private Observer<HttpResult<List<User>>> mRegisterObserver = new Observer<HttpResult<List<User>>>() {
        @Override
        public void onCompleted() {
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            errAction("");
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onNext(HttpResult<List<User>> result) {
            DialogUtil.dismissWaitDialog();
            if (result.getResult() == Constant.RESULT_ERROR) { //失败
                errAction(result.getErrorMessage());
                return;
            }

            switch (mPageType) {
                case Constant.REGISTER: //返回登录界面
                    CustomToast.showShortToast("注册成功, 请选择宝宝信息");
                    break;
                case Constant.FGT_PWD: //返回登录界面
                    CustomToast.showShortToast("修改密码成功 , 请登录");
                    DiaryApplication.mInstance.saveUser(null);
                    break;
            }

            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
            EventBus.getDefault().post(new CustomEvent(CustomEvent.ClOSE_SELF, 5));

            User user = result.getResdata().get(0);
            user.setPassword(passWord);

            //登录成功-- 判断是否进行过绑定操作&设置BabyInfo操作
            if (!TextUtils.isEmpty(user.getBabysex())) { //直接进入主页

                startActivity(new Intent(PassWordActivity.this, MainActivity.class));

                DiaryApplication.mInstance.saveUser(user);
            } else { //进入宝宝信息选择页
                Intent intent = new Intent(PassWordActivity.this, BabySexActivity.class);
                intent.putExtra(Constant.PHONE, user.getPhone());
                startActivity(intent);
                DiaryApplication.mInstance.saveUser(user);
            }

            /**
             * 账户统计
             */
            MobclickAgent.onProfileSignIn("LoginWay --" + 1, "  userID -- " + user.getPhone());

            finish();
        }
    };

    private void errAction(String errorMsg) {
        String text;
        if (TextUtils.isEmpty(errorMsg)) {
            text = "请检查网络链接";
        } else {
            text = errorMsg;
        }

        CustomToast.showShortToast(text);
    }

    void showWaitDialog(String text) {
        DialogUtil.showWaitDialog(PassWordActivity.this, text, false);
    }
}
